package com.example.framework.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.example.system.entity.ChatRecord;
import com.example.system.service.IChatRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @Author 王鹤蒲
 * @Date 2024 02 28
 */

@ServerEndpoint(value="/imServer")
@Component
public class WebSocketServer implements InitializingBean {

    private static final Logger logger= LoggerFactory.getLogger(WebSocketServer.class);

    public static final Map<String, Session> sessionMap=new ConcurrentHashMap<>();

    @Autowired
    private IChatRecordService iChatRecordService;

    static IChatRecordService staticIChatRecordService;

    @OnOpen
    public void onOpen(Session session){
        sessionMap.put(session.getId(),session);
        logger.info("[onOpen] 新建连接，session={}, 当前在线人数为：{}", session.getId(), sessionMap.size());
    }

    @OnClose
    public void onClose(Session session){
        sessionMap.remove(session.getId());
        logger.info("[onClose] 有一连接关闭，session={}, 当前在线人数为：{}", session.getId(), sessionMap.size());
    }

    @OnMessage
    public void onMessage(String message,Session fromSession){
        logger.info("服务端收到消息：{}",message);
        ChatRecord chatRecord= JSONUtil.toBean(message,ChatRecord.class);
        chatRecord.setTime(DateUtil.now());
        staticIChatRecordService.add(chatRecord);
        String jsonStr=JSONUtil.toJsonStr(chatRecord);
        this.sendAllMessage(jsonStr);
        logger.info("[OnMessage]发送消息：{}",jsonStr);
    }

    @OnError
    public void onError(Session session,Throwable error){
         logger.error("[OnError]会话发生错误",error);
    }

    private void sendMessage(Session fromSession,String message){
      sessionMap.values().forEach(session -> {
          if(fromSession!=session){
              logger.info("服务端给客户端[{}]发送消息{}",session.getId(),message);
              try {
                  session.getBasicRemote().sendText(message);
              } catch (Exception e) {
                  logger.error("服务端给客户端发送消息异常",e);
              }
          }
      });
    }

    private void sendAllMessage(String message){
        try {
            for(Session session:sessionMap.values()){
                logger.info("服务端给客户端[{}]发送消息{}",session.getId(),message);
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            logger.error("服务端给客户端发送消息失败",e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    staticIChatRecordService=iChatRecordService;
    }
}
